package com.xz.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.annotation.DataScope;
import com.xz.common.constant.UserConstants;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.entity.*;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.system.domain.*;
import com.xz.system.domain.dto.InsertTenantDto;
import com.xz.system.domain.vo.DictDataVo;
import com.xz.system.domain.vo.InitDataVo;
import com.xz.system.domain.vo.TenantBusinessVo;
import com.xz.system.mapper.SysMenuMapper;
import com.xz.system.mapper.SysRoleMapper;
import com.xz.system.mapper.SysRoleMenuMapper;
import com.xz.system.mapper.SysTenantMapper;
import com.xz.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * All rights Reserved, Designed By www.sunseagear.com
 *
 * @version V1.0
 * @package sys
 * @title: 租户管理控制器
 * @description: 租户管理控制器
 * @author: 未知
 * @date: 2019-11-28 06:24:52
 * @copyright: www.sunseagear.com Inc. All rights reserved.
 */
@Transactional
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysTenantMapper tenantMapper;
    @Autowired
    private ISysTenantService sysTenantService;
    @Autowired
    private IGraphicService iGraphicService;
    @Autowired
    private ISysTenantCommonConfigService sysTenantCommonConfigService;


    @Override
    public String checkNameOrCodeUnique(SysTenant entity)
    {
        Long tenantId = StringUtils.isNull(entity.getTenantId()) ? -1L : entity.getTenantId();
        SysTenant info = tenantMapper.checkUnique(entity.getTenantName(),entity.getTenantCode());
        if (StringUtils.isNotNull(info) && info.getTenantId().longValue() != tenantId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    //插入租户
    public boolean insertTenant(SysTenant sysTenant) {
        return  super.save(sysTenant);
    }

    @Override
    @Transactional
    public boolean save(SysTenant entity) {
        int count =count(new QueryWrapper<SysTenant>().eq("del_flag",0).eq("tenant_code",entity.getTenantCode()));
        if(count >0){
            return false;
        }
        //新增角色
        List<String> roleKeys = entity.getRoleKeys();
        if( null == roleKeys || entity.getTenantType() == 0){
            roleKeys = new ArrayList<>();
        }
        String business = roleKeys.stream().map(String::valueOf).collect(Collectors.joining(","));
        entity.setTenantBusiness(business);
        Integer tenantType = entity.getTenantType();


        entity.setCreateTime(new Date());
        super.save(entity);
        SysDept dept = new SysDept();
        dept.setDeptName(entity.getTenantName());
        dept.setLeader(entity.getTenantName());
        dept.setPhone(entity.getTenantPhone());
        dept.setTenantId(entity.getTenantId());
        dept.setCreateTime(new Date());
        dept.setCreateBy(entity.getCreateBy());
        sysDeptService.insertDept(dept);
        SysUser user = new SysUser();
        user.setDeptId(dept.getDeptId());
        user.setUserName(entity.getTenantName());
        user.setNickName(entity.getTenantName());
        user.setPhonenumber(entity.getTenantPhone());
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        user.setTenantId(entity.getTenantId());
        user.setCreateTime(new Date());
        user.setCreateBy(entity.getCreateBy());
        sysUserService.insertUser(user);
        //角色
        SysRole sysRole=new SysRole();
        sysRole.setRoleSort("0");
        sysRole.setStatus("0");
        sysRole.setTenantId(entity.getTenantId());
        sysRole.setCreateTime(new Date());
        if(tenantType == 0){
            sysRole.setRoleKey(entity.getTenantCode()+"_admin");
        }else{
            sysRole.setRoleKey(entity.getTenantCode()+"_tenantAdmin");
        }
        sysRole.setCreateBy(entity.getCreateBy());
        sysRole.setRoleName(entity.getTenantName()+"管理员");
        roleMapper.insert(sysRole);
        //租户配置--易出行配置
        SysTenantConfig sysTenantConfig = tenantMapper.selectSysTenantConfigById(1L);
        sysTenantConfig.setId(null);
        sysTenantConfig.setTenantId(entity.getTenantId());
        tenantMapper.insertSysTenantConfig(sysTenantConfig);

        List<SysMenu> menuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 0));
        //平台菜单
//        List<SysMenu> systemList = menuList.stream().filter(s -> s.getPermType() == 0).collect(Collectors.toList());
        //基础菜单
        List<SysMenu> basisMenu = menuList.stream().filter(s -> "1".equals(s.getPermType())).collect(Collectors.toList());
        //业务菜单
        List<SysMenu> businessMenu = menuList.stream().filter(s -> "2".equals(s.getPermType())&& business.contains(s.getBusiness())).collect(Collectors.toList());
        List<SysRoleMenu> roleMenus=new ArrayList<>();
        if(tenantType==1){
            if(CollectionUtils.isEmpty(roleKeys)|| roleKeys.size()==0){
                basisMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setRoleId(sysRole.getRoleId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenus.add(roleMenu);
                });

            }else{
                businessMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setRoleId(sysRole.getRoleId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenus.add(roleMenu);
                });
                basisMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenu.setRoleId(sysRole.getRoleId());
                    roleMenus.add(roleMenu);
                });

            }
        }else{
            menuList.forEach(s->{
                SysRoleMenu roleMenu=new SysRoleMenu();
                roleMenu.setMenuId(s.getMenuId());
                roleMenu.setPermType(s.getPermTypeInt());
                roleMenu.setRoleId(sysRole.getRoleId());
                roleMenus.add(roleMenu);
            });
        }
        roleMenuMapper.batchRoleMenu(roleMenus);

        sysUserService.insertUserAuth(user.getUserId(), new Long[]{sysRole.getRoleId()});
      /*  //插入内容
        List<Graphic> graphicList = iGraphicService.list(new QueryWrapper<Graphic>().eq("tenant_id", 1));
        if(graphicList!=null&&graphicList.size()>0){
            graphicList.stream().forEach(i->{
                i.setTenantId(entity.getTenantId());
                i.setGraphicId(null);
            });
            iGraphicService.saveBatch(graphicList);
        }*/

        return true;
    }

    @Override
    public SysTenant getSysTenantById(Long id) {
        SysTenant sysTenant = getById(id);
        if(!StringUtils.isEmpty(sysTenant.getTenantBusiness()) ) {
            sysTenant.setRoleKeys(Arrays.asList(sysTenant.getTenantBusiness().split(",")));
        }
        return sysTenant;
    }

    @Override
    public int deleteById(Long id,String username) {
        int count =sysUserService.count(new QueryWrapper<SysUser>().eq("tenant_id",id).eq("del_flag",0));
        if(count >0){
            throw new ServiceException("请先删除租户下的用户!");
        }
        count =sysDeptService.selectCountByTenantId(id);
        if(count >0){
            throw new ServiceException("请先删除租户下的部门!");
        }
        count = sysRoleService.selectCountByTenantId(id);
        if(count >0){
            throw new ServiceException("请先删除租户下的角色!");
        }
        SysTenant sysTenant  =baseMapper.selectById(id);
        sysTenant.setUpdateTime(new Date());
        sysTenant.setDelFlag("2");
        return baseMapper.updateById(sysTenant);
    }

    @Override
    @Transactional
    public int updateTenant(SysTenant sysTenant) {
    /*    List<String> roleKeys = sysTenant.getRoleKeys();
        if(null == roleKeys || sysTenant.getTenantType() == 0){
            roleKeys = new ArrayList<>();
        }
        String business=roleKeys.stream().map(String::valueOf).collect(Collectors.joining(","));
        sysTenant.setTenantBusiness(business);*/
        sysTenant.setUpdateTime(new Date());
        tenantMapper.updateById(sysTenant);
        /*SysTenant select = tenantMapper.selectById(sysTenant.getTenantId());
        SysRole role;
        if(select.getTenantType()==0){
            role=roleMapper.selectOne(new QueryWrapper<SysRole>().eq("tenant_id",sysTenant.getTenantId()).
                    eq("role_key",sysTenant.getTenantCode()+"_admin"));
        }else{
            role=roleMapper.selectOne(new QueryWrapper<SysRole>().
                    eq("tenant_id",sysTenant.getTenantId()).eq("role_key",sysTenant.getTenantCode()+"_tenantAdmin"));
        }
        Integer tenantType = sysTenant.getTenantType();
        roleMenuMapper.delete(new QueryWrapper<SysRoleMenu>().eq("role_id",role.getRoleId()));
        List<SysMenu> menuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("status", 0));
        //基础菜单
        List<SysMenu> basisMenu = menuList.stream().filter(s -> "1".equals(s.getPermType())).collect(Collectors.toList());
        //业务菜单
        List<SysMenu> businessMenu = menuList.stream().filter(s -> "2".equals(s.getPermType())&& business.contains(s.getBusiness())).collect(Collectors.toList());
        List<SysRoleMenu> roleMenus=new ArrayList<>();
        if(tenantType==1){
            if(CollectionUtils.isEmpty(roleKeys)|| roleKeys.size()==0){
                basisMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setRoleId(role.getRoleId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenus.add(roleMenu);
                });

            }else{
                businessMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setRoleId(role.getRoleId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenus.add(roleMenu);
                });
                basisMenu.forEach(s->{
                    SysRoleMenu roleMenu=new SysRoleMenu();
                    roleMenu.setMenuId(s.getMenuId());
                    roleMenu.setPermType(s.getPermTypeInt());
                    roleMenu.setRoleId(role.getRoleId());
                    roleMenus.add(roleMenu);
                });

            }
        }else{
            menuList.forEach(s->{
                SysRoleMenu roleMenu=new SysRoleMenu();
                roleMenu.setMenuId(s.getMenuId());
                roleMenu.setPermType(s.getPermTypeInt());
                roleMenu.setRoleId(role.getRoleId());
                roleMenus.add(roleMenu);
            });
        }
        //roleMenuMapper.batchRoleMenu(roleMenus);*/

        return 1;
    }

    @Override
    public int updateTenantConfig(SysTenantConfig sysTenantConfig) {
        int updateSysTenantConfig = tenantMapper.updateSysTenantConfig(sysTenantConfig);
        //删除模板
        tenantMapper.deleteTemplate(sysTenantConfig.getTenantId());
        //插入租户模板
        if(sysTenantConfig.getTemplate()!=null&&sysTenantConfig.getTemplate().size()>0){
            List<SysTenantTemplate> sysTenantTemplates=new ArrayList<>();
            sysTenantConfig.getTemplate().stream().forEach(item->{
                SysTenantTemplate sysTenantTemplate=new SysTenantTemplate();
                sysTenantTemplate.setTenantId(sysTenantConfig.getTenantId());
                sysTenantTemplate.setTemplateId(item);
                sysTenantTemplates.add(sysTenantTemplate);

            });
            if(sysTenantTemplates!=null&&sysTenantTemplates.size()>0){
                tenantMapper.insertTemplate(sysTenantTemplates);
            }

        }
        return updateSysTenantConfig;
    }

  @Override
  public int updateSysTenantConfig(SysTenantConfig sysTenantConfig) {
    int updateSysTenantConfig = tenantMapper.updateSysTenantConfig(sysTenantConfig);
    return updateSysTenantConfig;
  }

    @Override
    public SysTenantConfig getTenantConfig(Long id) {
        SysTenantConfig sysTenantConfig = tenantMapper.selectSysTenantConfigById(id);
        List<Long> longList = tenantMapper.selectTenantTemplate(id);
        if(Objects.nonNull(sysTenantConfig)){
            sysTenantConfig.setTemplate(longList);
        }
        return sysTenantConfig;
    }

    /**
     * 租户对应业务
     * @param id
     * @return
     */
    public AjaxResult tenantBusiness(Long id) {
        SysTenant sysTenant = getById(id);
        //租户是平台
        if(sysTenant.getTenantType()==0){
            return AjaxResult.success(sysDictDataService.tenantBusinessList(null));
        }
        //租户是商户
        if(StringUtils.isEmpty(sysTenant.getTenantBusiness())) {
           return AjaxResult.error("当前租户未开通业务");
        }
        String[] split = sysTenant.getTenantBusiness().split(",");
        return AjaxResult.success(sysDictDataService.tenantBusinessList(split));
    }

    /**
     * 门店端初始话数据
     * @return
     */
    public InitDataVo initData() {
        InitDataVo initDataVo=new InitDataVo();
        Long userId = SecurityUtils.getLoginUser().getUserId();
        Long tenantId = SecurityUtils.getLoginUser().getTenantId();
        //租户对应业务
        SysTenant sysTenant = sysTenantService.getSysTenantById(tenantId);
        String[] split = sysTenant.getTenantBusiness().split(",");
        List<DictDataVo> bizList = sysDictDataService.dictDataList("sys_business",split);
        initDataVo.setBizList(bizList);
        //订单状态
        List<DictDataVo> dictDataList = sysDictDataService.dictDataList("car_status",null);
        initDataVo.setCarStatusList(dictDataList);
        //订单来源
        List<DictDataVo> orderSource = sysDictDataService.dictDataList("sys_order_source",null);
        initDataVo.setOrderSource(orderSource);
        //当前登陆用户对应移动端菜单
        SysRole sysRole = sysRoleService.roleData(userId);
        //常用工具
        if(StringUtils.isNotBlank(sysRole.getCommonTools())){
            List<DictDataVo> list = sysDictDataService.dictDataList("common_tools",sysRole.getCommonTools().split(","));
            initDataVo.setCommonToolsList(list);
        }
        //首页模块
        if(StringUtils.isNotBlank(sysRole.getFinancialManagement())){
            List<DictDataVo> list = sysDictDataService.dictDataList("financial_management",sysRole.getFinancialManagement().split(","));
            initDataVo.setFinancialManagementList(list);
        }
        //运营报表
        if(StringUtils.isNotBlank(sysRole.getOperatingReports())){
            List<DictDataVo> list = sysDictDataService.dictDataList("operating_reports",sysRole.getOperatingReports().split(","));
            initDataVo.setOperatingReportsList(list);
        }
        //底部导航
        if(StringUtils.isNotBlank(sysRole.getNavigation())){
            List<DictDataVo> list = sysDictDataService.dictDataList("navigation",sysRole.getNavigation().split(","));
            initDataVo.setNavigationList(list);
        }
        //支付方式
        List<DictDataVo> sys_pay_way = sysDictDataService.dictDataList("sys_pay_way",null);
        initDataVo.setSysPayWay(sys_pay_way);
        //收费类型
        List<DictDataVo> charge_type = sysDictDataService.dictDataList("charge_type",null);
        initDataVo.setChargeType(charge_type);


        return initDataVo;
    }

    //数据字典
    public AjaxResult dictDataList(String dictType) {
        Map<String,Object> map=new HashMap<>();
        String[] split = dictType.split(",");
        for(String str :split){
            List<DictDataVo> list = sysDictDataService.dictDataList(str, null);
            map.put(str,list);
        }
        return AjaxResult.success(map);
    }

    @Override
    public List<Map<String, Object>> tenantList() {
        return baseMapper.tenantList();
    }

    /**
     * 商户信息--租户id
     * @param tenantId
     * @return
     */
    @Override
    public SysTenantConfig sysTenantConfigInfo(Long tenantId) {
        return baseMapper.sysTenantConfigInfo(tenantId);
    }

    /**
     * ota获取车牌信息
     * @return
     */
    @Override
    public AjaxResult getOtaSynvehicle() {
        Long tenantId = SecurityUtils.getLoginUser().getTenantId();
        SysTenantConfig sysTenantConfig = baseMapper.sysTenantConfigInfo(tenantId);
        if(Objects.isNull(sysTenantConfig) || sysTenantConfig.getEnableSyncTime() ==null){
            return AjaxResult.success(1);
        }
        return AjaxResult.success(sysTenantConfig.getEnableSyncTime()>2 || sysTenantConfig.getEnableSyncTime() <1 ? 1:sysTenantConfig.getEnableSyncTime());
    }
    /**
     *  ota修改同步车牌状态
     */
    @Override
    public AjaxResult updateOtaSynvehicle(SysTenantConfig sysTenantConfig) {
        Long tenantId = SecurityUtils.getLoginUser().getTenantId();
        SysTenantConfig tenantConfig = baseMapper.sysTenantConfigInfo(tenantId);
        tenantConfig.setEnableSyncTime(sysTenantConfig.getEnableSyncTime());
        int updated = baseMapper.updateSysTenantConfig(tenantConfig);
        return updated >0 ? AjaxResult.success() : AjaxResult.error();
    }
    //获取配置项
    @Override
    public String getTenantConfigValue(String key,Long tenantId) {
        List<SysTenantCommonConfig> tenantCommonConfigList = sysTenantCommonConfigService.selectSysTenantCommonConfigList(tenantId);
        if(!CollectionUtils.isEmpty(tenantCommonConfigList)){
            List<SysTenantCommonConfig> configList = tenantCommonConfigList.stream().filter(i -> key.equals(i.getTenantConfigKey())).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(configList)) {
                SysTenantCommonConfig sysTenantCommonConfig = configList.get(0);
                if (StringUtils.isNotEmpty(sysTenantCommonConfig.getTenantConfigValue())) {
                    return sysTenantCommonConfig.getTenantConfigValue();
                }
            }
        }
        return null;
    }
}
